package com.yunquan.ohana.ui.calendar.event.month

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.activity.result.ActivityResult
import androidx.core.view.doOnLayout
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.ui.BaseFragment
import com.yunquan.ohana.databinding.FragmentEventMonthBinding
import com.yunquan.ohana.ui.calendar.event.month.adapter.EventMonthBaseAdapter
import com.yunquan.ohana.utils.DateUtils
import java.time.LocalDateTime
import kotlin.math.ceil

class EventMonthFragment : BaseFragment<FragmentEventMonthBinding, EventMonthViewModel>() {


    companion object {
        fun newInstance(deviceId: String, userType: Boolean, offset: Int): EventMonthFragment {
            val fragment = EventMonthFragment()
            fragment.arguments = Bundle().apply {
                putInt("offset", offset)
                putString("deviceId", deviceId)
                putBoolean("userType",userType)
            }
            return fragment
        }
    }

    override fun initContentView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): Int {
        return R.layout.fragment_event_month
    }

    override fun initVariableId(): Int {
        return BR.eventMonthViewModel
    }

    override fun initData(savedInstanceState: Bundle?) {
        val bundle = requireArguments()
        val offset = bundle.getInt("offset")
        viewModel!!.mDeviceId = bundle.getString("deviceId")
        viewModel!!.mUserType = bundle.getBoolean("userType")
        // 月视图应按月份偏移，不能使用周偏移，否则相邻页可能仍处于同一个月导致数据相同
        viewModel!!.mCurrentDateTime = LocalDateTime.now().plusMonths(offset.toLong())

        val (start, end) = DateUtils.getMonthRange(viewModel!!.mCurrentDateTime!!)
        viewModel!!.mStartDate = start
        viewModel!!.mEndDate = end

        viewModel!!.initView()
    }

    override fun initViewObservable() {
        super.initViewObservable()
        viewModel!!.ui.observe(viewLifecycleOwner) {
            when (it) {
                0 -> {
                    binding!!.rvEvent.doOnLayout {
                        val rows = ceil(viewModel!!.items.size / 7.0).toInt()
                        val width = binding!!.rvEvent.width / 7
                        val height = binding!!.rvEvent.height / rows
                        binding!!.adapter = EventMonthBaseAdapter(width, height)
                    }
                }
            }
        }
    }

    override fun onActivityResult(result: ActivityResult) {
        super.onActivityResult(result)
        if (result.resultCode == 1002) {
            viewModel?.getEventData()
        } else if (result.resultCode == 1003) {
            viewModel?.getEventData()
        }
    }

}